/*eslint-disable*/
import Axios from 'axios';
import { message } from 'antd';
import envConfig from './env.config';
// import store from '../store/index';
// import Router from '../router/index';

const axiosInstance = Axios.create({
  baseURL: envConfig.baseUrl,
  timeout: 500000000,
});

// axiosInstance.defaults.retry = 4;
// axiosInstance.defaults.retryDelay = 1000;

axiosInstance.interceptors.request.use(
  (config) => {
    // const accessToken = store.state.login.requestHeader.mestoken;
    const accessToken = localStorage.getItem('mestoken')
      ? { mestoken: localStorage.getItem('mestoken') }
      : null;
    if (accessToken) {
      config.headers[envConfig.requestToken] = accessToken;
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

axiosInstance.interceptors.response.use(
  (response) => {
    if (response.data.code === 0) {
      return response.data;
    }
    if (response.data.code === envConfig.noAllowCode) {
      // 没有权限 跳转到登录页
      // Router.push({ path: '/login' });
    } else {
      message.error(response.data.msg);
      return Promise.reject(response.data);
    }
  },
  //  error => {
  //   message.error(error.response.data.message)
  //   return Promise.reject(error)
  // }
  (error) => {
    let code = 0;
    try {
      code = error.response.status;
    } catch (e) {
      if (!error.response) {
        // 断网了
        message.error({
          title: '您的网络有问题，请稍后再试',
          duration: 2500,
        });
        return Promise.reject(error);
      }
      if (error.toString().indexOf('Error: timeout') !== -1) {
        message.error({
          title: '网络请求超时',
          duration: 2500,
        });
        return Promise.reject(error);
      }
      if (error.toString().indexOf('Error: Network Error') !== -1) {
        message.error({
          title: '网络请求错误',
          duration: 2500,
        });
        return Promise.reject(error);
      }
    }

    if (code === 504) {
      message.error({
        title: '服务器异常',
        duration: 2500,
      });
      return Promise.reject(error);
    }

    if (code === 401) {
      message.error('登录状态已过期');
      // Router.push({ path: '/login' });
    } else if (code === 403) {
      message.error('拒绝访问');
    } else {
      const errorMsg = error.response.data.message;
      if (errorMsg !== undefined) {
        message.error(`${errorMsg}`);
      }
    }
    return Promise.reject(error);
  }
);

export default axiosInstance;
